package common

import (
	"backEnd/model"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtKey = []byte("my_secret_create")

type Claims struct {
	ID        uint
	Telephone string
	jwt.StandardClaims
}

func ReleaseToken(user model.User, expirationTime time.Time) (string, error) {
	//设置jwt负载
	claims := &Claims{
		ID:        user.ID,
		Telephone: user.Telephone,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "Ghtt",
			Subject:   "user token",
		},
	}

	//创建jwt
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	//使用密钥签名jwt并返回字符串jwt
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	return token, claims, err
}
